// UI控制器（改进版）
export class UIController {
    constructor() {
        this.tubesContainer = document.getElementById('tubes-container');
        this.currentLevelElement = document.getElementById('current-level');
        this.currentScoreElement = document.getElementById('current-score');
        this.currentMovesElement = document.getElementById('current-moves');
        this.hintCountElement = document.getElementById('hint-count');
        this.tubeCountElement = document.getElementById('tube-count');
        this.undoCountElement = document.getElementById('undo-count');
        
        this.winDialog = document.getElementById('win-dialog');
        this.hintDialog = document.getElementById('hint-dialog');
        
        // 存储试管位置信息
        this.tubePositions = new Map();
    }

    async bindEvents(game) {
        // 提示按钮
        document.getElementById('hint-btn').addEventListener('click', () => {
            game.getHint();
        });

        // 求助按钮
        document.getElementById('help-btn').addEventListener('click', () => {
            this.showMessage('求助功能暂未实现');
        });

        // 重新开始按钮
        document.getElementById('restart-btn').addEventListener('click', () => {
            game.resetGame();
        });

        // 撤销按钮
        document.getElementById('undo-btn').addEventListener('click', () => {
            game.undoMove();
        });

        // 添加空试管按钮
        document.getElementById('add-tube-btn').addEventListener('click', () => {
            game.addEmptyTube();
        });

        // 胜利对话框按钮
        document.getElementById('next-level-btn').addEventListener('click', () => {
            this.hideWinDialog();
            game.nextLevel();
        });

        document.getElementById('replay-btn').addEventListener('click', () => {
            this.hideWinDialog();
            game.resetGame();
        });

        // 提示对话框按钮
        document.getElementById('close-hint-btn').addEventListener('click', () => {
            this.hideHintDialog();
        });
    }

    async renderTubes(tubes) {
        this.tubesContainer.innerHTML = '';
        this.tubePositions.clear();
        
        for (const tube of tubes) {
            const tubeElement = await this.renderTube(tube);
            this.tubesContainer.appendChild(tubeElement);
            
            // 存储试管位置
            setTimeout(() => {
                const rect = tubeElement.getBoundingClientRect();
                this.tubePositions.set(tube.id, {
                    x: rect.left + rect.width / 2,
                    y: rect.top + rect.height / 2
                });
            }, 50);
        }
    }

    async renderTube(tube) {
        const tubeElement = document.createElement('div');
        tubeElement.className = 'tube';
        tubeElement.dataset.tubeId = tube.id;
        
        // 添加点击事件
        tubeElement.addEventListener('click', () => {
            if (window.gameInstance) {
                window.gameInstance.selectTube(tube.id);
            }
        });

        // 渲染液体层
        await this.renderLiquidLayers(tube, tubeElement);
        
        // 如果试管完成且有瓶塞，添加瓶塞
        if (tube.hasBottleCap) {
            const bottleCap = document.createElement('div');
            bottleCap.className = 'bottle-cap';
            tubeElement.appendChild(bottleCap);
        }

        return tubeElement;
    }

    async renderLiquidLayers(tube, container) {
        // 清空容器
        container.innerHTML = '';
        
        if (tube.isEmpty) {
            return;
        }

        // 分组相邻的同色液体
        const colorGroups = this.groupAdjacentColors(tube.colors);
        
        // 渲染每个颜色组
        for (const group of colorGroups) {
            const groupElement = document.createElement('div');
            groupElement.className = `liquid-group color-${group.color}`;
            groupElement.style.height = `${group.count * 30}px`;
            
            // 只在组的顶部添加分割线（如果不是最顶层）
            if (group !== colorGroups[colorGroups.length - 1]) {
                groupElement.classList.add('has-separator');
            }
            
            container.appendChild(groupElement);
        }
    }

    groupAdjacentColors(colors) {
        if (colors.length === 0) return [];
        
        const groups = [];
        let currentColor = colors[0];
        let currentCount = 1;
        
        for (let i = 1; i < colors.length; i++) {
            if (colors[i] === currentColor) {
                currentCount++;
            } else {
                groups.push({ color: currentColor, count: currentCount });
                currentColor = colors[i];
                currentCount = 1;
            }
        }
        
        // 添加最后一组
        groups.push({ color: currentColor, count: currentCount });
        
        return groups;
    }

    async highlightTube(tubeId, highlight, type = 'selected') {
        const tubeElement = document.querySelector(`[data-tube-id="${tubeId}"]`);
        if (!tubeElement) return;

        // 清除所有高亮状态
        tubeElement.classList.remove('selected', 'selecting', 'deselecting', 'target-highlight', 'hint-highlight');
        
        if (highlight) {
            switch (type) {
                case 'selected':
                    tubeElement.classList.add('selecting');
                    // 300ms后添加selected类，确保动画完成
                    setTimeout(() => {
                        tubeElement.classList.remove('selecting');
                        tubeElement.classList.add('selected');
                    }, 300);
                    break;
                    
                case 'target':
                    tubeElement.classList.add('target-highlight');
                    break;
                    
                case 'hint':
                    tubeElement.classList.add('hint-highlight');
                    break;
            }
        } else {
            if (type === 'selected' && tubeElement.classList.contains('selected')) {
                tubeElement.classList.remove('selected');
                tubeElement.classList.add('deselecting');
                // 300ms后移除deselecting类
                setTimeout(() => {
                    tubeElement.classList.remove('deselecting');
                }, 300);
            }
        }
    }

    // 获取试管位置
    getTubePosition(tubeId) {
        return this.tubePositions.get(tubeId) || { x: 0, y: 0 };
    }

    // 计算相对位置（左边还是右边）
    calculateRelativePosition(fromId, toId) {
        const fromPos = this.getTubePosition(fromId);
        const toPos = this.getTubePosition(toId);
        
        return fromPos.x < toPos.x ? 'right' : 'left';
    }

    // 更新试管位置
    async updateTubePosition(tubeId, position) {
        const tubeElement = document.querySelector(`[data-tube-id="${tubeId}"]`);
        if (tubeElement) {
            tubeElement.style.transform = `translate(${position.x}px, ${position.y}px)`;
            this.tubePositions.set(tubeId, position);
        }
    }

    async showHint(fromTubeId, toTubeId) {
        // 高亮提示的试管
        await this.highlightTube(fromTubeId, true, 'hint');
        await this.highlightTube(toTubeId, true, 'target');
        
        // 显示提示文本
        const hintText = document.getElementById('hint-text');
        hintText.textContent = `将试管 ${fromTubeId + 1} 的液体倒入试管 ${toTubeId + 1}`;
        this.showHintDialog();
        
        // 3秒后移除高亮
        setTimeout(() => {
            this.highlightTube(fromTubeId, false, 'hint');
            this.highlightTube(toTubeId, false, 'target');
        }, 3000);
    }

    async showWinDialog() {
        const winLevel = document.getElementById('win-level');
        const winScore = document.getElementById('win-score');
        const winMoves = document.getElementById('win-moves');
        
        if (window.gameInstance) {
            const game = window.gameInstance.gameState;
            winLevel.textContent = game.currentLevel;
            winScore.textContent = game.score;
            winMoves.textContent = game.moves;
        }
        
        this.winDialog.classList.remove('hidden');
    }

    hideWinDialog() {
        this.winDialog.classList.add('hidden');
    }

    showHintDialog() {
        this.hintDialog.classList.remove('hidden');
    }

    hideHintDialog() {
        this.hintDialog.classList.add('hidden');
    }

    async showMessage(message) {
        // 创建临时消息提示
        const messageElement = document.createElement('div');
        messageElement.className = 'message-toast';
        messageElement.textContent = message;
        messageElement.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 15px 25px;
            border-radius: 10px;
            z-index: 2000;
            font-size: 16px;
            text-align: center;
            animation: fadeInOut 2s ease-in-out;
        `;
        
        document.body.appendChild(messageElement);
        
        // 2秒后移除消息
        setTimeout(() => {
            if (messageElement.parentNode) {
                messageElement.parentNode.removeChild(messageElement);
            }
        }, 2000);
    }

    updateScore(score) {
        if (this.currentScoreElement) {
            this.currentScoreElement.textContent = score;
        }
    }

    updateLevel(level) {
        if (this.currentLevelElement) {
            this.currentLevelElement.textContent = level;
        }
    }

    updateMoves(moves) {
        if (this.currentMovesElement) {
            this.currentMovesElement.textContent = moves;
        }
    }

    updateHints(hints) {
        if (this.hintCountElement) {
            this.hintCountElement.textContent = hints;
        }
    }

    updateEmptyTubes(emptyTubes) {
        if (this.tubeCountElement) {
            this.tubeCountElement.textContent = emptyTubes;
        }
    }
}